package com.example.campus_order_sb.controller;

import com.example.campus_order_sb.dto.OrderResponse;
import com.example.campus_order_sb.dto.PlaceOrderRequest;
import com.example.campus_order_sb.entity.User;
import com.example.campus_order_sb.enums.OrderStatus;
import com.example.campus_order_sb.enums.UserType;
import com.example.campus_order_sb.repository.UserRepository;
import com.example.campus_order_sb.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/api/orders")
@CrossOrigin
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private UserRepository userRepository;

    @PostMapping
    public ResponseEntity<?> createOrder(@RequestBody PlaceOrderRequest orderRequest) {
        try {
            // 直接从请求体获取用户ID
            Integer userId = orderRequest.getUserId();
            if (userId == null) {
                Map<String, String> response = new HashMap<>();
                response.put("message", "用户ID不能为空");
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
            }

            OrderResponse createdOrder = orderService.createOrder(userId, orderRequest);
            return ResponseEntity.ok(createdOrder);
        } catch (Exception e) {
            Map<String, String> response = new HashMap<>();
            response.put("message", "创建订单失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
        }
    }

    @GetMapping
    public ResponseEntity<?> getUserOrders(@RequestParam Integer userId) {
        try {
            // 获取用户信息判断角色
            Optional<User> userOpt = userRepository.findById(userId);
            if (!userOpt.isPresent()) {
                Map<String, String> response = new HashMap<>();
                response.put("message", "用户不存在");
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
            }

            User user = userOpt.get();
            UserType userType = user.getUserType();

            List<OrderResponse> orders;
            if (userType == UserType.MERCHANT) {
                orders = orderService.getAllOrders();
            } else {
                orders = orderService.getUserOrders(userId);
            }
            return ResponseEntity.ok(orders);
        } catch (Exception e) {
            Map<String, String> response = new HashMap<>();
            response.put("message", "获取订单失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
        }
    }

    @GetMapping("/{orderId}")
    public ResponseEntity<?> getOrderById(
            @PathVariable Integer orderId,
            @RequestParam Integer userId) {
        try {
            // 获取用户信息判断角色
            Optional<User> userOpt = userRepository.findById(userId);
            if (!userOpt.isPresent()) {
                Map<String, String> response = new HashMap<>();
                response.put("message", "用户不存在");
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
            }

            OrderResponse order = orderService.getOrderById(orderId);

            User user = userOpt.get();
            UserType userType = user.getUserType();

            // 学生只能查看自己的订单
            if (userType == UserType.STUDENT && !order.getUserId().equals(userId)) {
                Map<String, String> response = new HashMap<>();
                response.put("message", "无权限查看该订单");
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body(response);
            }

            return ResponseEntity.ok(order);
        } catch (Exception e) {
            Map<String, String> response = new HashMap<>();
            response.put("message", "获取订单失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
        }
    }

    @PostMapping("/{orderId}/status")
    public ResponseEntity<?> updateOrderStatus(
            @PathVariable Integer orderId,
            @RequestBody Map<String, Object> requestBody) {

        try {
            Integer userId = (Integer) requestBody.get("userId");
            String statusStr = (String) requestBody.get("status");

            if (userId == null || statusStr == null) {
                Map<String, String> response = new HashMap<>();
                response.put("message", "用户ID和状态参数不能为空");
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
            }

            // 获取用户信息判断角色
            Optional<User> userOpt = userRepository.findById(userId);
            if (!userOpt.isPresent()) {
                Map<String, String> response = new HashMap<>();
                response.put("message", "用户不存在");
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
            }

            User user = userOpt.get();
            UserType userType = user.getUserType();

            // 只有商家可以更新订单状态
            if (userType != UserType.MERCHANT) {
                Map<String, String> response = new HashMap<>();
                response.put("message", "无权限执行此操作");
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body(response);
            }

            try {
                OrderStatus status = OrderStatus.valueOf(statusStr);
                OrderResponse updatedOrder = orderService.updateOrderStatus(orderId, status);
                return ResponseEntity.ok(updatedOrder);
            } catch (IllegalArgumentException e) {
                Map<String, String> response = new HashMap<>();
                response.put("message", "无效的订单状态: " + statusStr);
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
            }
        } catch (Exception e) {
            Map<String, String> response = new HashMap<>();
            response.put("message", "更新订单状态失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
        }
    }

    @PostMapping("/{orderId}/cancel")
    public ResponseEntity<?> cancelOrder(
            @PathVariable Integer orderId,
            @RequestParam Integer userId) {
        try {
            // 获取用户信息判断角色
            Optional<User> userOpt = userRepository.findById(userId);
            if (!userOpt.isPresent()) {
                Map<String, String> response = new HashMap<>();
                response.put("message", "用户不存在");
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
            }

            OrderResponse order = orderService.getOrderById(orderId);
            User user = userOpt.get();
            UserType userType = user.getUserType();

            // 学生只能取消自己的订单
            if (userType == UserType.STUDENT && !order.getUserId().equals(userId)) {
                Map<String, String> response = new HashMap<>();
                response.put("message", "无权限取消该订单");
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body(response);
            }

            // 检查订单状态是否允许取消
            if (order.getStatus() != OrderStatus.PENDING &&
                    order.getStatus() != OrderStatus.PAID &&
                    userType == UserType.STUDENT) {
                Map<String, String> response = new HashMap<>();
                response.put("message", "订单状态不允许取消");
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
            }

            OrderResponse cancelledOrder = orderService.cancelOrder(orderId);
            return ResponseEntity.ok(cancelledOrder);
        } catch (Exception e) {
            Map<String, String> response = new HashMap<>();
            response.put("message", "取消订单失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
        }
    }

    @PostMapping("/{orderId}/complete")
    public ResponseEntity<?> completeOrder(
            @PathVariable Integer orderId,
            @RequestParam Integer userId) {
        try {
            // 获取用户信息判断角色
            Optional<User> userOpt = userRepository.findById(userId);
            if (!userOpt.isPresent()) {
                Map<String, String> response = new HashMap<>();
                response.put("message", "用户不存在");
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
            }

            User user = userOpt.get();
            UserType userType = user.getUserType();

            // 只有商家可以完成订单
            if (userType != UserType.MERCHANT) {
                Map<String, String> response = new HashMap<>();
                response.put("message", "无权限执行此操作");
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body(response);
            }

            OrderResponse updatedOrder = orderService.updateOrderStatus(orderId, OrderStatus.COMPLETED);
            return ResponseEntity.ok(updatedOrder);
        } catch (Exception e) {
            Map<String, String> response = new HashMap<>();
            response.put("message", "完成订单失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
        }
    }
}